package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.domain.MultiDelayMessage;
import com.hmall.trade.constants.TradeMqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 监听订单支付状态的延迟消息监听器
 */
@Component
public class OrderStatusListener {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private PayClient payClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = TradeMqConstants.DELAY_ORDER_QUEUE, durable = "true"),
            exchange = @Exchange(value = TradeMqConstants.DELAY_EXCHANGE,
                    type = ExchangeTypes.TOPIC,delayed = "true"),
            key = TradeMqConstants.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenOrderCheckDelayMessage(MultiDelayMessage<Long> delayMessage){
        //- 1、获取订单id
        Long orderId = delayMessage.getData();
        //- 2、根据订单id查询订单；如果订单是已支付则不用再更新
        Order order = orderService.getById(orderId);
        if (order != null && order.getStatus() > 1) {
            //已经支付；不用再更新
            return;
        }
        //- 3、根据订单id查询 支付微服务pay-service里面的支付流水订单的状态是否为3（支付成功）
        PayOrderDTO payOrderDTO = payClient.queryByBizOrderNo(orderId);

        //- 3.1、如果已支付；则更新交易订单的状态为已支付
        if (payOrderDTO != null && payOrderDTO.getStatus() == 3) {
            orderService.markOrderPaySuccess(orderId);
            return;
        }
        //判断是否还有延迟时间片
        if (delayMessage.hasNextDelayMillis()) {
            //需要获取并移除时间片集合的第一个元素；
            Integer delayTime = delayMessage.removeDelayMillis();
            //再次发送一个延迟消息
            rabbitTemplate.convertAndSend(TradeMqConstants.DELAY_EXCHANGE, TradeMqConstants.DELAY_ORDER_ROUTING_KEY,
                    delayMessage, new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            message.getMessageProperties().setDelay(delayTime);
                            return message;
                        }
                    });
            return;
        }

        //- 3.2、如果未支付；则需要取消订单
        orderService.cancleOrder(orderId);
    }
}
